// pages/card/bind/index.js
const app = getApp()
import http from '../../../utils/request.js';
import alert from '../../../utils/alert.js';
import { $wuxCountDown } from '../../../wux/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bindCardNo:"",
    submitBtn:true,
    sendMobile:""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  formSubmit: function (e) {
    if (!(/^1[34578]\d{9}$/.test(e.detail.value.mobile))) {
      alert.alert("手机号码有误，请重填");
      return false;
    }
    var params = Object.assign({ app_id: app.globalData.app_id }, e.detail.value)
    http.post(app.config.service.bindCard, params).then(data => {
      alert.toast(data.msg)
      wx.navigateBack()
    }, err => {
      alert.alert(err)
    });
  },

  sendCode() {
    if (!(/^1[34578]\d{9}$/.test(this.data.sendMobile))) {
      alert("手机号码有误，请重填");
      return false;
    }

    if (this.c2 && this.c2.interval) return !1
    this.c2 = new $wuxCountDown({
      date: +(new Date) + 60000,
      onEnd() {
        this.setData({
          c2: '重新获取',
        })
      },
      render(date) {
        const sec = this.leadingZeros(date.sec, 2) + ' 秒 '
        date.sec !== 0 && this.setData({
          c2: sec,
        })
      },
    })

    http.post(
      app.config.service.sendCardBind, 
      { app_id: app.globalData.app_id, 
        mobile: this.data.sendMobile, 
        card_no: this.data.bindCardNo
      }).then(data => {
        alert.toast(data.msg)
      }, err => {
        alert.alert(err)
      });
  },
  checkCard: function (e) {
    http.post(app.config.service.checkCard, { app_id: app.globalData.app_id, card_no: this.data.bindCardNo }).then(data => {
      if (!(/^1[34578]\d{9}$/.test(data.mobile))) {
        alert.alert("卡号未绑定手机号或者手机号不合法,不能自助绑定");
        return false;
      }
      this.setData({
        sendMobile:data.mobile,
        submitBtn:false
      })
    }, err => {
      alert.alert(err)
    });
  },
  bindCardNo:function(e){
    this.setData({
      bindCardNo:e.detail.value
    })
  }
})